package spider.service;

import com.htiiot.common.db.DbConnectionPool;
import com.htiiot.common.db.JDBCUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import spider.http.HTTPUtil;
import spider.pojo.DeviceFailure;
import spider.pojo.DeviceFailureList;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public class DeviceFailureService {
    private static Logger logger = LogManager.getLogger(DeviceFailureService.class);
    public static void getDeviceFailure(){
        DbConnectionPool pool = DbConnectionPool.getPool();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = pool.getConnection();
            String sql = "select name,device_id from tz_device where tenant_id > 0 AND device_id  > 0";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                String name = rs.getString(1);
                int deviceId = rs.getInt(2);
                //logger.info("get device data  name is "+name +" -- deviceid is "+deviceId);
                List<DeviceFailureList> deviceFailureLists = HTTPUtil.get("http://outwardApi.hence.cn/api/Devices/getFailure?Token=d04259b9c0a3ccabedae048c1d3bef3f&&DeviceID=" + name, DeviceFailureList.class);
                if (deviceFailureLists != null && deviceFailureLists.size() > 0) {
                    DeviceFailureList deviceFailureList = deviceFailureLists.get(0);
                    String rescode = deviceFailureList.getRescode();
                    if ("00".equals(rescode)) {
                        conn.setAutoCommit(false);
                        String sqlFail = "insert into tz_device_failure(date,device_id,total_cnt,month_cnt,remaining_time) values (now(),?,?,?,?)";
                        ps = conn.prepareStatement(sqlFail);
                        ps.clearBatch();
                        List<DeviceFailure> deviceFailList = deviceFailureList.getData();
                        for (int i = 0; i < deviceFailList.size(); i++) {
                            DeviceFailure deviceFailure = deviceFailList.get(i);
                            logger.info("get failure data is --> "+deviceFailure);
                            ps.setInt(1, deviceId);
                            ps.setString(2, deviceFailure.getTotalCnt());
                            ps.setString(3, deviceFailure.getLastMonthCnt());
                            ps.setString(4, deviceFailure.getRemainingTime());
                            ps.addBatch();
                        }
                        ps.executeBatch();
                    }
                }
            }
        }catch (SQLException e){
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JDBCUtils.close(ps, rs, conn);
        }
    }

    public static void updateDeviceFailure(){
        logger.info("update Device Failure ");
        DbConnectionPool pool = DbConnectionPool.getPool();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = pool.getConnection();
            String sql = "select name,device_id from tz_device where tenant_id > 0 AND device_id  > 0";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                String name = rs.getString(1);
                int deviceId = rs.getInt(2);
                logger.info("get device data  name is " + name + " -- deviceid is " + deviceId);
                String url = "http://outwardApi.hence.cn/api/Devices/getFailure?Token=d04259b9c0a3ccabedae048c1d3bef3f&&DeviceID=" + name;
                logger.info("request updateDeviceFailure url is : " + url);
                List<DeviceFailureList> deviceFailureLists = HTTPUtil.get(url, DeviceFailureList.class);
                if (deviceFailureLists != null && deviceFailureLists.size() > 0) {
                    DeviceFailureList deviceFailureList = deviceFailureLists.get(0);
                    String rescode = deviceFailureList.getRescode();
                    if ("00".equals(rescode)) {
                        try {
                            conn.setAutoCommit(false);
                            String sqlFail = "insert into tz_device_failure(date,device_id,total_cnt,month_cnt,remaining_time) values (now(),?,?,?,?)  ON DUPLICATE KEY UPDATE total_cnt =? ,month_cnt = ?,remaining_time = ?";
                            ps = conn.prepareStatement(sqlFail);
                            ps.clearBatch();
                            List<DeviceFailure> deviceFailList = deviceFailureList.getData();
                            for (int i = 0; i < deviceFailList.size(); i++) {
                                DeviceFailure deviceFailure = deviceFailList.get(i);
                                logger.info("get failure data is --> " + deviceFailure);
                                ps.setInt(1, deviceId);
                                ps.setString(2, deviceFailure.getTotalCnt());
                                ps.setString(3, deviceFailure.getLastMonthCnt());
                                ps.setString(4, deviceFailure.getRemainingTime());
                                ps.setString(5, deviceFailure.getTotalCnt());
                                ps.setString(6, deviceFailure.getLastMonthCnt());
                                ps.setString(7, deviceFailure.getRemainingTime());
                                ps.addBatch();
                            }
                            ps.executeBatch();
                        } catch (SQLException e) {
                            try {
                                conn.rollback();
                            } catch (SQLException e1) {
                                e1.printStackTrace();
                            }
                            e.printStackTrace();
                        } finally {
                            try {
                                conn.commit();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }catch (SQLException e){
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
                e.printStackTrace();
        }finally {
            JDBCUtils.close(ps, rs, conn);
        }
    }
}
